﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Logic;
using Logic.ClarizenSvc;

namespace ClarizenGadget.Controllers
{
    
    
    public class EntitiesController : Controller
    {
        public static Condition GetFilter(String filterName)
        {
            switch (filterName)
            {
                case "userFilter":
                    if (!string.IsNullOrEmpty(BLL.Users.CurrentClarizenID))
                        return new Or
                        {
                            Conditions = new Condition[]{ 
                                    new Compare{LeftExpression=new FieldExpression{FieldName="DirectManager"}, Operator = Operator.Equal, RightExpression= new ConstantExpression{Value = new EntityId{TypeName="User", Value = BLL.Users.CurrentClarizenID}}},
                                    new Compare{LeftExpression=new EntityIdExpression(), Operator = Operator.Equal, RightExpression= new ConstantExpression{Value =  BLL.Users.CurrentClarizenID}}
                                }
                        };
                    else return new Or();
                default:
                    return null;
            }
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Search(String name, String q, int page = 0)
        {
            Boolean hasMore;
            long totalCount;
            Exception err;
            List<GenericEntity> res;

            if (name == "Project")
            {
                res = new QueryComponent().GetWorkItems(WorkItemType.Project, WorkItemFilter.IHaveAnyRole, WorkItemState.All, out hasMore, out totalCount, out err, q, fields: new string[]{"Name"}, UsePaging: true, PageNumber: page, returnCount: true).Select(wi => wi.ToGenericEntity()).ToList();
            }
            else
            {

                string filterName = Request["filter"] == null ? "" : Request["filter"];
                res = new QueryComponent().GetListByTypeName(typeName: name, hasMore: out hasMore, search: q, count: 20, page: page, totalCount: out totalCount, getTotalCount: page == 0, conditions: GetFilter(Request["filter"]));
            }
            
            var ret = new {Elements = res.Select(r => new { ID = r.Id, Name = r.Name }), HasMore = hasMore, total= totalCount};
            return Json(new GadgetResponse<Object> { Status = GadgetResponseStatus.Success, Data = ret });
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete(String id, String type)
        {
            try
            {
                new QueryComponent().DeleteEntity(new EntityId { TypeName = type, Value = id });
                return Json(new GadgetResponse<Object> { Status = GadgetResponseStatus.Success, Data = true });
            }
            catch(Exception e)
            {
                return Json(new GadgetResponse<Object> { Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }
    }
}
